﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Yuebon.Commons.Encrypt;
using Yuebon.Commons.Helpers;
using Yuebon.Commons.Log;
using Yuebon.Commons.Models;
using Yuebon.Commons.Tree;
using Yuebon.Shop.Application;
using Yuebon.Shop.Dtos;
using Yuebon.Shop.IServices;
using Yuebon.Shop.Models;
using Yuebon.WebApp.Controllers;

namespace Yuebon.WebApp.Areas.Shop.Controllers
{
    [Area("Shop")]
    [Route("Shop/[controller]/[action]")]
    public class MembersController :  BusinessController<Members, IMembersService>
    {
        public MembersController(IMembersService _iService) : base(_iService)
        {
            iService = _iService;

            AuthorizeKey.InsertKey = "Members/Add";
            AuthorizeKey.UpdateKey = "Members/Edit";
            AuthorizeKey.DeleteKey = "Members/Delete";
            AuthorizeKey.UpdateEnableKey = "Members/Enable";
            AuthorizeKey.ListKey = "Members/List";
            AuthorizeKey.ViewKey = "Members/View";
        }

        /// <summary>
        /// 新增会员前对字段的默认处理
        /// </summary>
        /// <returns>指定对象的集合</returns>
        protected override void OnBeforeInsert(Members info)
        {
            //留给子类对参数对象进行修改
            info.Id = GuidUtils.CreateNo();
            info.CreateDate = DateTime.Now;
            info.ReferralUserId = "";
            if (string.IsNullOrEmpty(info.Password))
            {
                info.PasswordSalt = MD5Util.GetMD5_32(info.UserName + "12345678").Substring(0, 16).ToLower();
                info.Password = QQEncryptUtil.EncodePasswordWithVerifyCode("12345678", info.PasswordSalt);
            }
            else
            {
                info.PasswordSalt = MD5Util.GetMD5_32(info.UserName + info.Password).Substring(0, 16).ToLower();
                info.Password = QQEncryptUtil.EncodePasswordWithVerifyCode(info.Password, info.PasswordSalt);

            };
            if (string.IsNullOrEmpty(info.TradePassword))
            {
                info.IsOpenBalance = false;
            }
            else {
                info.TradePasswordSalt = MD5Util.GetMD5_32(info.UserName + info.TradePassword).Substring(0, 32).ToLower();
                info.TradePassword = QQEncryptUtil.EncodePasswordWithVerifyCode(info.TradePassword, info.TradePasswordSalt);
                info.IsOpenBalance = true;
            };
            info.OrderNumber = 0;
            info.Expenditure = 0;
            info.Points = 0;
            info.Balance = 0;
            info.RequestBalance = 0;
            info.TopRegionId = 0;
            info.RegionId = 0;
            info.EmailVerification = false;
            info.CellPhoneVerification = false;
            info.RegisteredSource = 0;
            info.IsQuickLogin = false;
            info.IsSubscribe = false;

        }

        /// <summary>
        /// 修改会员前对字段的默认处理
        /// </summary>
        /// <returns>指定对象的集合</returns>
        protected override void OnBeforeUpdate(Members info)
        {
            CommonResult result = new CommonResult();
            Members members= iService.Get(info.Id);
            if (!string.IsNullOrEmpty(info.Password))
            {
                if (members.Password != info.Password)
                {
                    info.PasswordSalt = MD5Util.GetMD5_32(info.UserName + info.Password).Substring(0, 16).ToLower();
                    info.Password = QQEncryptUtil.EncodePasswordWithVerifyCode(info.Password, info.PasswordSalt);
                }
            };
            if (!string.IsNullOrEmpty(info.TradePassword))
            {
                if (members.TradePassword != info.TradePassword) {
                    info.TradePasswordSalt = MD5Util.GetMD5_32(info.UserName + info.TradePassword).Substring(0, 32).ToLower();
                    info.TradePassword = QQEncryptUtil.EncodePasswordWithVerifyCode(info.TradePassword, info.TradePasswordSalt);
                    info.IsOpenBalance = true;
                }
            }
            else
            {
                info.IsOpenBalance = false;
            };
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <returns>指定对象的集合</returns>
        [HttpGet]
        public  IActionResult GetAll()
        {

            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.ListKey);
            IEnumerable<Members> list = iService.GetAll();
            var treeList = new List<TreeSelectModel>();
            foreach (Members item in list)
            {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.Id;
                treeModel.text = item.UserName+"/"+item.NickName+"("+item.RealName+")";
                treeModel.parentId = "";
                treeList.Add(treeModel);
            }
            return ToJsonContent(treeList.TreeSelectJson());

        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <returns>指定对象的集合</returns>
        [HttpGet]
        public override IActionResult FindWithPager()
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.ListKey);
            string keywords = Request.Query["search"].ToString() == null ? "" : Request.Query["search"].ToString();
            string orderByDir = Request.Query["order"].ToString() == null ? "" : Request.Query["order"].ToString();
            string orderFlied = Request.Query["sort"].ToString() == "" ? "Id" : Request.Query["sort"].ToString();
            string where = GetPagerCondition();
            bool order = orderByDir == "asc" ? false : true;
            if (!string.IsNullOrEmpty(keywords))
            {
                where += string.Format(" and (UserName like '%{0}%' or RealName like '%{0}%' or NickName like '%{0}%' or IdentityCard like '%{0}%')", keywords);
            }
            PagerInfo pagerInfo = GetPagerInfo();
            MembersApp membersApp = new MembersApp();
            List<MembersDto> list = membersApp.FindWithPager(where, pagerInfo, orderFlied, order);

            //构造成Json的格式传递
            var result = new
            {
                total = pagerInfo.RecordCount,
                rows = list
            };
            return ToJsonContent(result);
        }

    }
}